<template>
  <div class="tenant-package">
    <div class="page-content">
      <el-card class="package-card">
        <template #header>
          <div class="card-header">
            <span>租户套餐列表</span>
            <el-space>
              <el-button type="primary" @click="handleAdd">
                <el-icon><Plus /></el-icon>
                新增套餐
              </el-button>
              <el-button @click="goBack">
                <el-icon><Back /></el-icon>
                返回租户管理
              </el-button>
            </el-space>
          </div>
        </template>

        <!-- 搜索表单 -->
        <el-form
          v-show="showSearch"
          ref="queryRef"
          :model="queryParams"
          :inline="true"
          label-width="80px"
          class="search-form"
        >
          <el-form-item label="套餐名称" prop="packageName">
            <el-input 
              v-model="queryParams.packageName" 
              placeholder="请输入套餐名称" 
              clearable 
              @keyup.enter="handleQuery" 
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option label="正常" value="1" />
              <el-option label="停用" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 数据表格 -->
        <el-table
          v-loading="loading"
          :data="packageList"
          border
          @row-click="handleRowClick"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="套餐ID" align="center" prop="packageId" width="100" />
          <el-table-column label="套餐名称" align="center" prop="packageName" width="150" />
          <el-table-column label="关联菜单" align="center" prop="menuIds" width="200" show-overflow-tooltip />
          <el-table-column label="备注" align="center" prop="remark" width="200" show-overflow-tooltip />
          <el-table-column label="状态" align="center" width="80">
            <template #default="{ row }">
              <el-tag :type="row.status === '1' ? 'success' : 'danger'">
                {{ row.status === '1' ? '正常' : '停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
          <el-table-column label="操作" align="center" fixed="right" width="220">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleDetail(row)">详情</el-button>
              <el-button type="warning" link @click="handleUpdate(row)">编辑</el-button>
              <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-show="pagination.total > 0"
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageChange"
          @current-change="handlePageChange"
        />
      </el-card>
    </div>

    <!-- 新增/编辑套餐对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="packageFormRef"
        :model="packageForm"
        :rules="packageRules"
        label-width="100px"
      >
        <el-form-item label="套餐名称" prop="packageName">
          <el-input v-model="packageForm.packageName" placeholder="请输入套餐名称" />
        </el-form-item>
        <el-form-item label="关联菜单" prop="menuIds">
          <el-input v-model="packageForm.menuIds" placeholder="请输入关联菜单ID，多个用逗号分隔" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="packageForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注" 
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="packageForm.status">
            <el-radio label="1">正常</el-radio>
            <el-radio label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="套餐详情"
      width="600px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="套餐ID">{{ currentDetail.packageId }}</el-descriptions-item>
        <el-descriptions-item label="套餐名称">{{ currentDetail.packageName }}</el-descriptions-item>
        <el-descriptions-item label="关联菜单" :span="2">{{ currentDetail.menuIds }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentDetail.remark }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="currentDetail.status === '1' ? 'success' : 'danger'">
            {{ currentDetail.status === '1' ? '正常' : '停用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ currentDetail.createTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Back, Search, Refresh } from '@element-plus/icons-vue';
import { 
  listTenantPackage, 
  getTenantPackage,
  addTenantPackage,
  updateTenantPackage,
  delTenantPackage 
} from '@/api/tenant/package';

defineOptions({
  name: 'TenantPackage',
});

const router = useRouter();

// 响应式数据
const loading = ref(false);
const showSearch = ref(true);
const packageList = ref<any[]>([]);
const dialogVisible = ref(false);
const detailDialogVisible = ref(false);
const dialogTitle = ref('');
const queryRef = ref();
const packageFormRef = ref();

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  packageName: undefined as string | undefined,
  status: undefined as string | undefined,
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

// 套餐表单
const packageForm = reactive({
  packageId: undefined as number | undefined,
  packageName: '',
  menuIds: '',
  remark: '',
  status: '1',
});

// 当前详情
const currentDetail = reactive({
  packageId: '',
  packageName: '',
  menuIds: '',
  remark: '',
  status: '',
  createTime: '',
});

// 表单验证规则
const packageRules = {
  packageName: [{ required: true, message: '套餐名称不能为空', trigger: 'blur' }],
};

// 方法
const handleQuery = () => {
  queryParams.pageNum = 1;
  pagination.current = 1;
  getList();
};

const resetQuery = () => {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    packageName: undefined,
    status: undefined,
  });
  pagination.current = 1;
  getList();
};

const getList = async () => {
  loading.value = true;
  try {
    const response = await listTenantPackage({
      ...queryParams,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    });
    packageList.value = response.rows || [];
    pagination.total = response.total || 0;
  } catch (error) {
    console.error('获取租户套餐列表失败:', error);
    ElMessage.error('获取租户套餐列表失败');
  } finally {
    loading.value = false;
  }
};

const handleAdd = () => {
  resetForm();
  dialogVisible.value = true;
  dialogTitle.value = '新增租户套餐';
};

const handleDetail = async (row: any) => {
  try {
    const response = await getTenantPackage(row.packageId);
    Object.assign(currentDetail, response.data);
    detailDialogVisible.value = true;
  } catch (error) {
    console.error('获取套餐详情失败:', error);
    ElMessage.error('获取套餐详情失败');
  }
};

const handleUpdate = async (row: any) => {
  resetForm();
  try {
    const response = await getTenantPackage(row.packageId);
    Object.assign(packageForm, response.data);
    dialogVisible.value = true;
    dialogTitle.value = '编辑租户套餐';
  } catch (error) {
    console.error('获取套餐详情失败:', error);
    ElMessage.error('获取套餐详情失败');
  }
};

const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `是否确认删除租户套餐编号为"${row.packageId}"的数据项？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    return delTenantPackage(row.packageId);
  }).then(() => {
    getList();
    ElMessage.success('删除成功');
  }).catch(() => {
    // 用户取消删除
  });
};

const goBack = () => {
  router.push('/tenant/list');
};

const handlePageChange = () => {
  queryParams.pageNum = pagination.current;
  queryParams.pageSize = pagination.pageSize;
  getList();
};

const handleRowClick = (row: any) => {
  console.log('点击行:', row);
};

const handleSubmit = () => {
  packageFormRef.value.validate((valid: boolean) => {
    if (valid) {
      const submitFunc = packageForm.packageId ? updateTenantPackage : addTenantPackage;
      submitFunc(packageForm).then(() => {
        ElMessage.success(packageForm.packageId ? '修改成功' : '新增成功');
        dialogVisible.value = false;
        getList();
      }).catch((error: any) => {
        console.error('提交失败:', error);
        ElMessage.error('操作失败');
      });
    }
  });
};

const handleDialogClose = () => {
  resetForm();
};

const resetForm = () => {
  Object.assign(packageForm, {
    packageId: undefined,
    packageName: '',
    menuIds: '',
    remark: '',
    status: '1',
  });
  packageFormRef.value?.resetFields();
};

// 生命周期
onMounted(() => {
  console.log('[TenantPackage] 组件已挂载');
  getList();
});
</script>

<style scoped>
.tenant-package {
  padding: 20px;
}


.page-content {
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}

.package-card {
  border: none;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>
